var express = require("express"),
	app = express(),
	server = require("http").createServer(app),
	port = parseInt(process.env.PORT,10) || 8000;


var http = require('http');
var io = require('socket.io').listen(80);

//app.use(express.bodyParser());
app.configure(function(){
	app.use(express.methodOverride());
	app.use(express.bodyParser());
	app.use(express.static(__dirname+'/public/'));
	app.use(express.errorHandler({
		dumpExceptions: true,
		showStack: true
	}));
});

var roomCounter = 0;
var globalData = {
	rooms:[{
		name: "FirstRoom",
		id: roomCounter++,
		users: ["dabs","sigga","joi"],
		messages: ["12","12"] }],
};

var openConnections = [];

app.get('/', function(req, res){
  res.redirect("/index.html");
});

app.post('/login', function (req, res) {
	var post = req.body.nick;
	console.log(post);

	
	//req.socket.username = post;
	//users.push(req.body);
	res.send(200);
});

app.get("/rooms",function(req,res){
	//res.json(res.UserId);
	//console.log("req.socket.id " + req.socket.id);
  	res.json(globalData);
});

app.post('/room/:id',function(req,res) {
	var newUser = req.body.nick;
	console.log("test");
	for(var i = 0; i<globalData.rooms.length;i++){
		if(globalData.rooms[i].id == req.params.id){
			globalData.rooms[i].users.push(newUser);
			break;
		}
		
	}

});

app.post('/room/create', function(req,res){
	var post = req.body;
	console.log("req.body.channel " + post.channel);
	var room ={
		name: post.channel,
		id: roomCounter++,
		messages:[]
	};
	globalData.rooms.push(room);
	
	res.json(globalData);
});

app.get('/room/:id', function(req,res){
	data = "Not found";
	for(var i = 0; i<globalData.rooms.length;i++){
		if(globalData.rooms[i].id == req.params.id){
			data =  globalData.rooms[i];
			break;
		}
		
	}

	res.json(data);
});
app.get("/room/:id/update",function(req,res){
	req.socket.setTimeout(Infinity);
		res.writeHead(200, {
	        'Content-Type': 'text/event-stream',
	        'Cache-Control': 'no-cache',
	        'Connection': 'keep-alive'
	    });
	    openConnections.push(res);
	    res.write('\n');
	    
	    
	    

	    req.on("close", function() {
	        var toRemove;
	        for (var j =0 ; j < openConnections.length ; j++) {
	            if (openConnections[j] == res) {
	                toRemove =j;

	                break;
	            }
	        }
	        openConnections.splice(j,1);
	        console.log("openConnections.length " + openConnections.length);
	    });
});

app.post("/room/:id/sendMessage",function(req,res){
	var post = req.body;
	console.log(req.body);
	console.log("sendMessage.Username "+post.nick);
	for(var i = 0; i<globalData.rooms.length;i++){
		if(globalData.rooms[i].id == req.params.id){
			globalData.rooms[i].messages.push(post.name+": "+post.msg);
			break;
		}
		
	}
	res.send(200);
	test(req.socket.username+": "+post.message);
	


});

function test(message){

	 openConnections.forEach(function(resp) {
        var d = new Date();
        resp.write('id: ' + d.getMilliseconds() + '\n');
        resp.write('data:' + message +   '\n\n'); // Note the extra newline

      
    });
}






app.listen(port);